package com.ssy.lingxi.member.merchant.serviceimpl.web;

import com.ssy.lingxi.common.constant.basic.EnableDisableStatus;
import com.ssy.lingxi.common.constant.order.OrderSourceKindEnum;
import com.ssy.lingxi.common.constant.order.OrderTypeEnum;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.common.utils.DateTimeUtil;
import com.ssy.lingxi.member.merchant.entity.MemberOrderCommentDO;
import com.ssy.lingxi.member.merchant.model.vo.comment.request.WaitCommentOrderQueryVO;
import com.ssy.lingxi.member.merchant.model.vo.comment.response.WaitCommentOrderPageVO;
import com.ssy.lingxi.member.merchant.repository.MemberOrderCommentRepository;
import com.ssy.lingxi.member.merchant.service.base.IBaseMemberCacheService;
import com.ssy.lingxi.member.merchant.service.web.IMemberOrderCommentService;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 会员订单评价服务实现类
 * @author yzc
 * @version 2.0.0
 * @date 2021/8/3
 */
@Service
public class MemberOrderCommentServiceImpl implements IMemberOrderCommentService {

    @Resource
    private MemberOrderCommentRepository memberOrderCommentRepository;

    @Resource
    private IBaseMemberCacheService memberCacheService;


    /**
     * 采购会员 - 待评价订单
     * @param headers Http头部信息
     * @param pageVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<WaitCommentOrderPageVO>> pageBuyerWaitCommentOrder(HttpHeaders headers, WaitCommentOrderQueryVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);

        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), Sort.by("createTime").descending());
        Page<MemberOrderCommentDO> pageList = memberOrderCommentRepository.findAll((Specification<MemberOrderCommentDO>) (root, query, cb) -> {
            List<Predicate> predicateList = new ArrayList<>();
            predicateList.add(cb.equal(root.get("buyerMemberId"), loginUser.getMemberId()));
            predicateList.add(cb.equal(root.get("buyerRoleId"), loginUser.getMemberRoleId()));
            predicateList.add(cb.equal(root.get("buyerCompleteCommentStatus"), EnableDisableStatus.DISABLE.getCode()));

            // 非SRM订单(SRM订单含有物料,不能评价)
            predicateList.add(cb.notEqual(root.get("orderKind").as(Integer.class), OrderSourceKindEnum.SRM.getCode()));

            if (StringUtils.isNotEmpty(pageVO.getOrderNo())) {
                predicateList.add(cb.like(root.get("orderNo"), "%" + pageVO.getOrderNo() + "%"));
            }

            if (StringUtils.isNotEmpty(pageVO.getDigest())) {
                predicateList.add(cb.like(root.get("digest"), "%" + pageVO.getDigest() + "%"));
            }

            if (StringUtils.isNotEmpty(pageVO.getMemberName())) {
                predicateList.add(cb.like(root.get("vendorMemberName"), "%" + pageVO.getMemberName() + "%"));
            }

            if (Objects.nonNull(pageVO.getCreateTimeStart())) {
                LocalDateTime startDateTime = DateTimeUtil.parseDateTime(pageVO.getCreateTimeStart());
                predicateList.add(cb.greaterThanOrEqualTo(root.get("createTime"), startDateTime));
            }

            if (Objects.nonNull(pageVO.getCreateTimeEnd())) {
                LocalDateTime endDateTime = DateTimeUtil.parseDateTime(pageVO.getCreateTimeEnd());
                predicateList.add(cb.lessThanOrEqualTo(root.get("createTime"), endDateTime));
            }

            if (Objects.nonNull(pageVO.getOrderType())) {
                predicateList.add(cb.equal(root.get("orderType"), pageVO.getOrderType()));
            }

            Predicate[] p = new Predicate[predicateList.size()];
            return query.where(predicateList.toArray(p)).getRestriction();
        }, page);

        List<WaitCommentOrderPageVO> resultList = pageList.stream().map(e -> {
            WaitCommentOrderPageVO waitCommentOrderPageVO = new WaitCommentOrderPageVO();
            waitCommentOrderPageVO.setId(e.getId());
            waitCommentOrderPageVO.setOrderNo(e.getOrderNo());
            waitCommentOrderPageVO.setDigest(e.getDigest());
            waitCommentOrderPageVO.setMemberName(e.getVendorMemberName());
            waitCommentOrderPageVO.setCreateTime(DateTimeUtil.formatDateTime(e.getCreateTime()));
            waitCommentOrderPageVO.setTotalAmount(e.getTotalAmount());
            waitCommentOrderPageVO.setOrderType(e.getOrderType());
            waitCommentOrderPageVO.setOrderTypeName(OrderTypeEnum.getNameByCode(e.getOrderType()));
            waitCommentOrderPageVO.setInnerStatus(e.getBuyerInnerStatus());
            waitCommentOrderPageVO.setInnerStatusName("已完成");
            waitCommentOrderPageVO.setOuterStatus(e.getOuterStatus());
            waitCommentOrderPageVO.setOuterStatusName("已完成");
            waitCommentOrderPageVO.setCompleteCommentStatus(e.getBuyerCompleteCommentStatus());
            return waitCommentOrderPageVO;
        }).collect(Collectors.toList());

        return Wrapper.success(new PageData<>(pageList.getTotalElements(), resultList));
    }

    /**
     * 供应会员 - 待评价订单
     * @param headers Http头部信息
     * @param pageVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<WaitCommentOrderPageVO>> pageVendorWaitCommentOrder(HttpHeaders headers, WaitCommentOrderQueryVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);

        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), Sort.by("createTime").descending());
        Page<MemberOrderCommentDO> pageList = memberOrderCommentRepository.findAll((Specification<MemberOrderCommentDO>) (root, query, cb) -> {
            List<Predicate> predicateList = new ArrayList<>();
            predicateList.add(cb.equal(root.get("vendorMemberId"), loginUser.getMemberId()));
            predicateList.add(cb.equal(root.get("vendorRoleId"), loginUser.getMemberRoleId()));
            predicateList.add(cb.equal(root.get("vendorCompleteCommentStatus"), EnableDisableStatus.DISABLE.getCode()));

            // 非SRM订单(SRM订单含有物料,不能评价)
            predicateList.add(cb.notEqual(root.get("orderKind").as(Integer.class), OrderSourceKindEnum.SRM.getCode()));

            if (StringUtils.isNotEmpty(pageVO.getOrderNo())) {
                predicateList.add(cb.like(root.get("orderNo"), "%" + pageVO.getOrderNo() + "%"));
            }

            if (StringUtils.isNotEmpty(pageVO.getDigest())) {
                predicateList.add(cb.like(root.get("digest"), "%" + pageVO.getDigest() + "%"));
            }

            if (StringUtils.isNotEmpty(pageVO.getMemberName())) {
                predicateList.add(cb.like(root.get("buyerMemberName"), "%" + pageVO.getMemberName() + "%"));
            }

            if (Objects.nonNull(pageVO.getCreateTimeStart())) {
                LocalDateTime startDateTime = DateTimeUtil.parseDateTime(pageVO.getCreateTimeStart());
                predicateList.add(cb.greaterThanOrEqualTo(root.get("createTime"), startDateTime));
            }

            if (Objects.nonNull(pageVO.getCreateTimeEnd())) {
                LocalDateTime endDateTime = DateTimeUtil.parseDateTime(pageVO.getCreateTimeEnd());
                predicateList.add(cb.lessThanOrEqualTo(root.get("createTime"), endDateTime));
            }

            if (Objects.nonNull(pageVO.getOrderType())) {
                predicateList.add(cb.equal(root.get("orderType"), pageVO.getOrderType()));
            }

            Predicate[] p = new Predicate[predicateList.size()];
            return query.where(predicateList.toArray(p)).getRestriction();
        }, page);

        List<WaitCommentOrderPageVO> resultList = pageList.stream().map(e -> {
            WaitCommentOrderPageVO waitCommentOrderPageVO = new WaitCommentOrderPageVO();
            waitCommentOrderPageVO.setId(e.getId());
            waitCommentOrderPageVO.setOrderNo(e.getOrderNo());
            waitCommentOrderPageVO.setDigest(e.getDigest());
            waitCommentOrderPageVO.setMemberName(e.getBuyerMemberName());
            waitCommentOrderPageVO.setCreateTime(DateTimeUtil.formatDateTime(e.getCreateTime()));
            waitCommentOrderPageVO.setTotalAmount(e.getTotalAmount());
            waitCommentOrderPageVO.setOrderType(e.getOrderType());
            waitCommentOrderPageVO.setOrderTypeName(OrderTypeEnum.getNameByCode(e.getOrderType()));
            waitCommentOrderPageVO.setInnerStatus(e.getVendorInnerStatus());
            waitCommentOrderPageVO.setInnerStatusName("已完成");
            waitCommentOrderPageVO.setOuterStatus(e.getOuterStatus());
            waitCommentOrderPageVO.setOuterStatusName("已完成");
            waitCommentOrderPageVO.setCompleteCommentStatus(e.getVendorCompleteCommentStatus());
            return waitCommentOrderPageVO;
        }).collect(Collectors.toList());

        return Wrapper.success(new PageData<>(pageList.getTotalElements(), resultList));
    }
}
